package com.seafood.entity;

import lombok.Data;
import lombok.EqualsAndHashCode;

import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;

/**
 * 短信验证码实体类
 */
@Data
@EqualsAndHashCode(callSuper = true)
@Entity
@Table(name = "sms_verification_codes")
public class SmsVerificationCode extends BaseEntity {
    
    @NotBlank(message = "手机号不能为空")
    @Column(name = "phone", nullable = false, length = 20)
    private String phone;
    
    @NotBlank(message = "验证码不能为空")
    @Column(name = "code", nullable = false, length = 10)
    private String code;
    
    @NotNull(message = "验证码类型不能为空")
    @Enumerated(EnumType.STRING)
    @Column(name = "code_type", nullable = false)
    private CodeType codeType;
    
    @Column(name = "is_used")
    private Boolean isUsed = false;
    
    @NotNull(message = "过期时间不能为空")
    @Column(name = "expire_time", nullable = false)
    private LocalDateTime expireTime;
    
    @Column(name = "used_time")
    private LocalDateTime usedTime;
    
    @Column(name = "ip_address", length = 50)
    private String ipAddress;
    
    @Column(name = "user_agent", length = 500)
    private String userAgent;
    
    @Column(name = "attempts")
    private Integer attempts = 0;
    
    @Column(name = "max_attempts")
    private Integer maxAttempts = 3;
    
    /**
     * 验证码类型枚举
     */
    public enum CodeType {
        REGISTER,           // 注册验证
        LOGIN,              // 登录验证
        RESET_PASSWORD,     // 重置密码
        CHANGE_PHONE,       // 修改手机号
        ORDER_CONFIRM,      // 订单确认
        PAYMENT_CONFIRM,    // 支付确认
        SECURITY_VERIFY     // 安全验证
    }
    
    /**
     * 检查验证码是否有效
     */
    public boolean isValid() {
        return !isUsed && 
               expireTime.isAfter(LocalDateTime.now()) && 
               attempts < maxAttempts;
    }
    
    /**
     * 检查验证码是否过期
     */
    public boolean isExpired() {
        return expireTime.isBefore(LocalDateTime.now());
    }
    
    /**
     * 增加尝试次数
     */
    public void incrementAttempts() {
        this.attempts++;
    }
    
    /**
     * 标记为已使用
     */
    public void markAsUsed() {
        this.isUsed = true;
        this.usedTime = LocalDateTime.now();
    }
}